import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login.vue'
import SqlTranslator from '../components/SqlTranslator.vue'
import AdminDashboard from '../components/AdminDashboard.vue'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/translator'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/translator',
      name: 'translator',
      component: SqlTranslator,
      meta: { requiresAuth: true, role: 'ROLE_USER' }
    },
    {
      path: '/admin',
      name: 'admin',
      component: AdminDashboard,
      meta: { requiresAuth: true, role: 'ROLE_ADMIN' }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    // 未登录，重定向到登录页
    next('/login')
  } else if (to.meta.requiresAuth && to.meta.role) {
    // 检查角色权限
    const userRole = userStore.userInfo.role
    
    if (to.meta.role === 'ROLE_ADMIN' && userRole !== 'ROLE_ADMIN') {
      // 普通用户尝试访问管理员页面，重定向到翻译器页面
      next('/translator')
    } else if (to.meta.role === 'ROLE_USER' && userRole === 'ROLE_ADMIN' && to.path === '/') {
      // 管理员访问根路径时，重定向到管理员页面
      next('/admin')
    } else {
      // 角色匹配，允许访问
      next()
    }
  } else {
    // 无需权限或已登录且权限足够
    next()
  }
})

export default router 